package com.ruoyi.project.data.service.impl;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.data.domain.WeightStationCamera;
import com.ruoyi.project.data.domain.WeightStationEnterpriseTypeRecord;
import com.ruoyi.project.data.mapper.WeightStationCameraMapper;
import com.ruoyi.project.data.mapper.WeightStationEnterpriseTypeRecordMapper;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysDictDataMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.project.data.mapper.WeightStationMapper;
import com.ruoyi.project.data.domain.WeightStation;
import com.ruoyi.project.data.service.IWeightStationService;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import org.springframework.util.CollectionUtils;

/**
 * 场站信息Service业务层处理
 *
 * @author ruoyi
 * @date 2020-03-21
 */
@Service
public class WeightStationServiceImpl implements IWeightStationService
{
    private static final Logger logger = LoggerFactory.getLogger(WeightStationServiceImpl.class);

    @Autowired
    private WeightStationMapper weightStationMapper;

     @Autowired
    private  WeightStationCameraMapper stationCameraMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private WeightStationEnterpriseTypeRecordMapper enterpriseTypeRecordMapper;


    @Value("${video.ip}")
    private String  ip;

    @Value("${video.appKey}")
    private String  appKey;

    @Value("${video.appSecret}")
    private String  appSecret;

    @Value("${video.keyPath}")
    private String  keyPath;


   static {
       ArtemisConfig.host ="218.90.184.190";
       ArtemisConfig.appKey ="27244333";
       ArtemisConfig.appSecret ="lUxqimU0lvl4tACvY2ol";
   }


    /**
     * 查询场站信息
     *
     * @param id 场站信息ID
     * @return 场站信息
     */
    @Override
    public WeightStation selectWeightStationById(Long id)
    {
        WeightStation station = weightStationMapper.selectWeightStationById(id);
        handleEnterpriseTypeData(station);
        List<Map<String, Object>> areaList = weightStationMapper.getAreaList("3202");
        if (StringUtils.isNotEmpty(station.getJurisdictionUnit()) && areaList.size() > 0) {
            for(Map<String, Object> areaMap : areaList) {
                if(areaMap.get("areaCode").equals(station.getJurisdictionUnit())) {
                    station.setJurisdictionUnitName(areaMap.get("areaName").toString());
                    break;
                }
            }
            areaList = weightStationMapper.getAreaList(station.getJurisdictionUnit());
            if (StringUtils.isNotEmpty(station.getTown()) && areaList.size() > 0) {
                for(Map<String, Object> areaMap : areaList) {
                    if(areaMap.get("areaCode").equals(station.getTown())) {
                        station.setTownName(areaMap.get("areaName").toString());
                        break;
                    }
                }
            }
        }
        return station;
    }

    /**
     * 查询场站信息列表
     *
     * @param weightStation 场站信息
     * @return 场站信息
     */
    @Override
    public List<WeightStation> selectWeightStationList(WeightStation weightStation)
    {
        handleEnterpriseTypeData(weightStation);
        List<WeightStation> list = weightStationMapper.selectWeightStationList(weightStation);
        if(list != null && list.size() > 0) {
            List<Map<String, Object>> areaList = weightStationMapper.getAreaList("3202");
            SysDictData dictData = new SysDictData();
            dictData.setDictType("station_jgdw");//监管单位
            List<SysDictData> stationJGDWList = dictDataMapper.selectDictDataList(dictData);
            dictData.setDictType("station_xz");//企业性质
            List<SysDictData> stationXZList = dictDataMapper.selectDictDataList(dictData);

            for(WeightStation station : list) {
                if (StringUtils.isNotEmpty(station.getJurisdictionUnit()) && list.size() > 0) {
                    for(Map<String, Object> areaMap : areaList) {
                        if(areaMap.get("areaCode").equals(station.getJurisdictionUnit())) {
                            station.setJurisdictionUnit(areaMap.get("areaName").toString());
                            break;
                        }
                    }
                }
                if (StringUtils.isNotEmpty(station.getSupervisionUnit()) && list.size() > 0) {
                    for (SysDictData dicData: stationJGDWList) {
                        if(dicData.getDictValue().equals(station.getSupervisionUnit())) {
                            station.setSupervisionUnitForChinese(dicData.getDictLabel());
                            break;
                        }
                    }
                }
                if (StringUtils.isNotEmpty(station.getEnterpriseTypeString()) && list.size() > 0) {
                    String enterpriseTypeJoinStr = null;
                    List<String> enterpriseChineseList = new ArrayList<>();
                    List<String> enterpriseTypeList = Arrays.asList(station.getEnterpriseTypeString().split(","));
                    for (String type: enterpriseTypeList) {
                        for (SysDictData dicData: stationXZList) {
                            if(dicData.getDictValue().equals(type)) {
                                enterpriseChineseList.add(dicData.getDictLabel());
                                break;
                            }
                        }
                    }
                    enterpriseTypeJoinStr = StringUtils.join(enterpriseChineseList.toArray(), ",");
                    station.setEnterpriseTypeStringForChinese(enterpriseTypeJoinStr);
                }
            }
        }
        return list;
    }

    /**
     * 新增场站信息
     *
     * @param weightStation 场站信息
     * @return 结果
     */
    @Override
    public int insertWeightStation(WeightStation weightStation)
    {
        handleEnterpriseTypeData(weightStation);
        // 根据属地编号获取该属地场站编号最大值
        String code = weightStation.getTown();
        String maxStationCode = weightStationMapper.selectMaxStationCode(code);
        String stationCode = "";
        weightStation.joinToString(weightStation.getEnterpriseType());
        if(maxStationCode == null || "".equals(maxStationCode)) {
            stationCode = code + "001";
        }else {
            stationCode = String.valueOf(Long.parseLong(maxStationCode) + 1);
        }
        weightStation.setStationCode(stationCode);
        // 判断场站编号是否存在
        int count = weightStationMapper.checkStationCodeUnique(weightStation);
        if(count > 0) {
            return 0;
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        weightStation.setCreateId(user.getUserId().toString());
        weightStation.setCreateTime(DateUtils.getNowDate());
        // 根据地址获取经纬度
        if (StringUtils.isNotBlank(weightStation.getAddress())){
            Map lngAndLat = LngAndLatUtils.getLngAndLat(weightStation.getAddress());
            if (lngAndLat != null){
                weightStation.setLongitude(String.valueOf(lngAndLat.get("lng")));
                weightStation.setLatitude(String.valueOf(lngAndLat.get("lat")));
            }
        }
        int i = weightStationMapper.insertWeightStation(weightStation);
        String [] enterpriseType = weightStation.getEnterpriseType();
        if(enterpriseType !=null && enterpriseType.length > 0) {
            for (String type : enterpriseType) {
                WeightStationEnterpriseTypeRecord enterpriseTypeRecord = new WeightStationEnterpriseTypeRecord();
                enterpriseTypeRecord.setEnterpriseType(type);
                enterpriseTypeRecord.setStationId(weightStation.getId());
                enterpriseTypeRecordMapper.insertWeightStationEnterpriseTypeRecord(enterpriseTypeRecord);
            }
        }
        Map<String, Object> accountMap = new HashMap<String, Object>();
        accountMap.put("userName", stationCode);
        accountMap.put("password", StringUtils.getUUID_32());
        accountMap.put("token", StringUtils.getUUID_32());
        // 添加接口账号
        weightStationMapper.insertApiAccount(accountMap);
        return i;
    }

    private  String getSixCode(){
        Random rad=new Random();
        String result  = rad.nextInt(1000000) +"";
        if(result.length()!=6){
            return getSixCode();
        }
        return result;
    }

    /**
     * 修改场站信息
     *
     * @param weightStation 场站信息
     * @return 结果
     */
    @Override
    public int updateWeightStation(WeightStation weightStation)
    {
        handleEnterpriseTypeData(weightStation);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        weightStation.setUpdateId(user.getUserId().toString());
        weightStation.setUpdateTime(DateUtils.getNowDate());
        // 根据地址修改经纬度
        WeightStation station = weightStationMapper.selectWeightStationById(weightStation.getId());
        if (!station.getAddress().equals(weightStation.getAddress())){
            Map lngAndLat = LngAndLatUtils.getLngAndLat(weightStation.getAddress());
            if (lngAndLat != null){
                weightStation.setLongitude(String.valueOf(lngAndLat.get("lng")));
                weightStation.setLatitude(String.valueOf(lngAndLat.get("lat")));
            }
        }
        String [] enterpriseType = weightStation.getEnterpriseType();
        if(enterpriseType !=null && enterpriseType.length > 0){
            enterpriseTypeRecordMapper.deleteWeightStationEnterpriseTypeRecordByStationId(weightStation.getId());
            for(String type: enterpriseType){
                WeightStationEnterpriseTypeRecord enterpriseTypeRecord = new WeightStationEnterpriseTypeRecord();
                enterpriseTypeRecord.setEnterpriseType(type);
                enterpriseTypeRecord.setStationId(weightStation.getId());
                enterpriseTypeRecordMapper.insertWeightStationEnterpriseTypeRecord(enterpriseTypeRecord);
            }
        }
        return weightStationMapper.updateWeightStation(weightStation);
    }

    /**
     * 批量删除场站信息
     *
     * @param ids 需要删除的场站信息ID
     * @return 结果
     */
    @Override
    public int deleteWeightStationByIds(Long[] ids)
    {
        for (Long id: ids) {
            enterpriseTypeRecordMapper.deleteWeightStationEnterpriseTypeRecordByStationId(id);
            WeightStation station = weightStationMapper.selectWeightStationById(id);
            if(station != null) {
                weightStationMapper.deleteweightUserTokenByStationCode(station.getStationCode());
            }
        }
        return weightStationMapper.deleteWeightStationByIds(ids);
    }

    /**
     * 删除场站信息信息
     *
     * @param id 场站信息ID
     * @return 结果
     */
    @Override
    public int deleteWeightStationById(Long id)
    {
        enterpriseTypeRecordMapper.deleteWeightStationEnterpriseTypeRecordByStationId(id);
        WeightStation station = weightStationMapper.selectWeightStationById(id);
        if(station != null) {
            weightStationMapper.deleteweightUserTokenByStationCode(station.getStationCode());
        }
        return weightStationMapper.deleteWeightStationById(id);
    }

    @Override
    public List<Map<String, Object>> getAreaList(String areaCode) {
        List<Map<String, Object>> areaList = weightStationMapper.getAreaList(areaCode);
        return areaList;
    }

    /**
     *  通过场站id 获取场站视频播放地址
     * @param stationId
     * @return
     */
    @Override
    public AjaxResult getVideoPath(String stationId) {
        WeightStation station = weightStationMapper.selectWeightStationById(Long.parseLong(stationId));
        if("320205".equals(station.getJurisdictionUnit())){
            /**
             * 获取场站视频代码
             */
            List<WeightStationCamera>  stationList=stationCameraMapper.selectStationCameraList(stationId);

            String cameraCodes=stationList.stream().map(weightStationCamera -> weightStationCamera.getCameraCode()).collect(Collectors.joining(","));
            if (StringUtils.isEmpty(cameraCodes)){
                return  AjaxResult.error("场站没有相机");
            }

            final String getSecurityApi = "/artemis/api/artemis/v1/agreementService/securityParam/appKey/"+appKey;
            Map<String, String> path = new HashMap<String, String>(2){
                {
                    put("https://", getSecurityApi);
                }
            };

            String result = ArtemisHttpUtil.doGetArtemis(path, null,null,null,null);


            JSONObject json= JSON.parseObject(result);

            if (!"0".equals(json.getString("code"))){
                return  AjaxResult.error("请求系统参数错误");
            }
            JSONObject  data=json.getJSONObject("data");

            String  time=data.getString("time");
            String  timeSecret=data.getString("timeSecret");
            String  appSecret=data.getString("appSecret");

            StringBuilder  str=new StringBuilder();

            str.append("hikvideoclient://ReqType:PlayReal;VersionTag:artemis;SvrIp:");
            str.append(ip);
            str.append(";");
            str.append("SvrPort:443;");
            str.append("Appkey:");
            str.append(appKey);
            str.append(";");
            str.append("AppSecret:");
            str.append(appSecret);
            str.append(";");
            str.append("time:");
            str.append(time);
            str.append(";");
            str.append("timesecret:");
            str.append(timeSecret);
            str.append(";");
            str.append("httpsflag:1;");
            str.append("CamList:");
            str.append(cameraCodes);
            str.append(";");

            Map<String,String > dd=new HashMap<>();
            dd.put("urltt",str.toString());
            return  AjaxResult.success(dd);
        }else{
            // 根据场站编号或者相机
            WeightStationCamera camera = new WeightStationCamera();
            camera.setStationCode(station.getStationCode());
            // 根据场站编号获取场站相机
            List<WeightStationCamera> list = stationCameraMapper.selectCameraVideoList(camera);
            if(list == null || list.size() ==0){
                return AjaxResult.error("暂未配置相机编号");
            }
            List<WeightStationCamera> vdeoList = new ArrayList<>();
            for(WeightStationCamera c : list){
                WeightStationCamera videoMap = new WeightStationCamera();
                if("320282".equals(station.getJurisdictionUnit())){     // 宜兴
                    if(c.getVideoUrl() != null && !"".equals(c.getVideoUrl())){
                        videoMap.setVideoUrl(c.getVideoUrl());
                        videoMap.setCaneraName(c.getCaneraName());
                        vdeoList.add(videoMap);
                    }
                }else if("320214".equals(station.getJurisdictionUnit())){     // 新区
                    try {
                        String json = VideoUtils.liveXq(c.getCameraCode());
                        JSONObject object = JSON.parseObject(json);
                        if(object.getInteger("code")==20000){
                            JSONObject data = object.getJSONObject("data");
                            String url = data.getString("url");
                            videoMap.setVideoUrl(url);
                            videoMap.setCaneraName(c.getCaneraName());
                            vdeoList.add(videoMap);
                        }else{
                            logger.error("新区直播接口返回错误，原因:"+json);
                        }
                    } catch (Exception e) {
                        logger.error("新区直播接口返回错误，原因:"+e.getMessage());
                        e.printStackTrace();
                    }
                }else if("320281".equals(station.getJurisdictionUnit()) || "320206".equals(station.getJurisdictionUnit()) || "320213".equals(station.getJurisdictionUnit())){    // 江阴、惠山、梁溪
                    try {
                        String json = VideoUtils.liveXs(c.getCameraCode());
                        JSONObject object = JSON.parseObject(json);
                        if("0".equals(object.getString("code"))){
                            JSONObject data = object.getJSONObject("data");
                            String url = data.getString("url");
                            videoMap.setVideoUrl(url);
                            videoMap.setCaneraName(c.getCaneraName());
                            vdeoList.add(videoMap);
                        }else{
                            logger.error("锡山直播接口返回错误，原因:"+json);
                        }
                    } catch (Exception e) {
                        logger.error("锡山直播接口返回错误，原因:"+e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
            if(vdeoList.size()==0){
                return AjaxResult.error("该场站暂无实时视频");
            }
            return AjaxResult.success(vdeoList);
        }
    }

    /**
     *  通过场站id 获取场站视频回放地址
     * @param stationId
     * @return
     */
    @Override
    public AjaxResult getBackVideoPath(String stationId,String startTime) {
        /**
         * 获取场站视频代码
         */
        List<WeightStationCamera>  stationList=stationCameraMapper.selectStationCameraList(stationId);

        // String cameraCodes=stationList.stream().map(weightStationCamera -> weightStationCamera.getCameraCode()).collect(Collectors.joining(","));
       List<String> cameraList=stationList.stream().map(weightStationCamera -> weightStationCamera.getCameraCode()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(cameraList)){
            return  AjaxResult.error("场站没有相机");
        }

        final String getSecurityApi = "/artemis/api/artemis/v1/agreementService/securityParam/appKey/"+appKey;
        Map<String, String> path = new HashMap<String, String>(2){{
                put("https://", getSecurityApi);
            }};

        String result = ArtemisHttpUtil.doGetArtemis(path, null,null,null,null);

        JSONObject json= JSON.parseObject(result);

        if (!"0".equals(json.getString("code"))){
            return  AjaxResult.error("请求系统参数错误");
        }
        JSONObject  data=json.getJSONObject("data");

        String  time=data.getString("time");
        String  timeSecret=data.getString("timeSecret");
        String  appSecret=data.getString("appSecret");

        Date date = null;
        try {
             date=DateUtils.parseDate(startTime,"yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        }


        SysDictData  sysDictData= new SysDictData();
        sysDictData.setDictType("vedio_time");
        sysDictData.setDictLabel("back_time");

       List<SysDictData> dictList=  dictDataMapper.selectDictDataList(sysDictData);

       Long  tim=Long.parseLong(dictList.get(0).getDictValue());

        Long start=date.getTime()/1000;

        Long end=null;
       if(tim < 0){
           end = start -tim;
           start = start + tim;
       }else{
           end = start + tim;
           start = start - tim;
       }

        StringBuilder  str=new StringBuilder();

     /*   var param = 'hikvideoclient://ReqType:' + PlayBack + ';' + 'VersionTag:artemis' + ';' + 'SvrIp:' + SvrIp + ';'
                + 'SvrPort:' + SvrPort + ';' + 'Appkey:' + appkey + ';' + 'AppSecret:' + appSecret + ';' + 'time:' +
                time + ';' + 'timesecret:' + timeSecret + ';' + 'httpsflag:' + httpsflag + ';'
                + 'CamList:' + CamList + '_' + startTime + '_' + endTime + ';';*/

        str.append("hikvideoclient://ReqType:PlayBack;VersionTag:artemis;SvrIp:");
        str.append(ip);
        str.append(";");
        str.append("SvrPort:443;");
        str.append("Appkey:");
        str.append(appKey);
        str.append(";");
        str.append("AppSecret:");
        str.append(appSecret);
        str.append(";");
        str.append("time:");
        str.append(time);
        str.append(";");
        str.append("timesecret:");
        str.append(timeSecret);
        str.append(";");
        str.append("httpsflag:1;");
        str.append("CamList:");
        for (int i=0; i<cameraList.size();i++){
            str.append(cameraList.get(i));
            str.append("_");
            str.append(start);
            str.append("_");
            str.append(end);
            if (i<cameraList.size()){
                str.append(",");
            }
        }
        str.append(";");

        Map<String,String > dd=new HashMap<>();
        dd.put("videoUrl",str.toString());
        return  AjaxResult.success(dd);
    }

    @Override
    public List<WeightStation> selectStationGpsList(WeightStation weightStation) {
        return weightStationMapper.selectStationGpsList(weightStation);
    }

    @Override
    public List<WeightStation> selectNoWeightStationList(WeightStation weightStation) {
        List<WeightStation> list = weightStationMapper.selectNoWeightStationList(weightStation);
        if(list != null && list.size() > 0) {
            List<Map<String, Object>> areaList = weightStationMapper.getAreaList("3202");

            for(WeightStation station : list) {
                if (StringUtils.isNotEmpty(station.getJurisdictionUnit()) && list.size() > 0) {
                    for(Map<String, Object> areaMap : areaList) {
                        if(areaMap.get("areaCode").equals(station.getJurisdictionUnit())) {
                            station.setJurisdictionUnit(areaMap.get("areaName").toString());
                            break;
                        }
                    }
                }
            }
        }
        return list;
    }

    /**
     * 转换EnterpriseType
     * @param weightStation
     */
    private void handleEnterpriseTypeData(WeightStation weightStation){
        if(weightStation!=null && weightStation.getEnterpriseType() != null && weightStation.getEnterpriseType().length>0){
            weightStation.joinToString(weightStation.getEnterpriseType());
        }
        if(weightStation!=null && StringUtils.isNotNull(weightStation.getEnterpriseTypeString()) && StringUtils.isNotEmpty(weightStation.getEnterpriseTypeString())){
            weightStation.splitFromString(weightStation.getEnterpriseTypeString());
        }
    }
}
